// JavaScript Document
$(document).ready(function() {
  var module_alert = $("#module").val(); //name of the module/functionality to display in alert box
  var pageno, action;
	
  //Date picker for date search in subject listing page
  $('#edit-site-search-date').datepicker({
    dateFormat:'mm-dd-yy'
  });
  //Date picker for date search in subject listing page
  $('#edit-comp-search-date').datepicker({
    dateFormat:'mm-dd-yy'
  });

  $("#edit-company-add-new").click(function(){
    addNewCompanyDialog('new', 600, 310, 'Add Legal Entity');
    return false;
  });
  $("#edit-company-apply").click(function(){
    applyCompanyFilterAction(1, action);
    return false;
  });
});

function applyFilterAction(pageno, action, companyId){

  //prepare the field values for filtering
  var site_name = $.trim($("#edit-site-search-name").val());
  var company_name = $.trim($("#edit-site-company-name").val());
  var site_desc = $("#edit-site-search-desc").val();
  var site_url = $("#edit-site-search-url").val();
  var site_status = $("#edit-site-search-status").val();
  var site_date	= $("#edit-site-search-date").val();
  var sort = $('#hid_sort').val();
  if(companyId == 0){
      companyId = $('#hid_company_id').val();
  }  
  //check for search criteria and return false if no value
  if (site_name == "" && site_desc == "" && site_url == "" && site_status == "") {
    openAlertDialog(300, 125, 'Information', 'Please enter the search criteria');
    return;
  }

  $('#listingResultset').html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  $("#pagingdivtop").hide();
  $("#pagingdivbottom").hide();

  $.ajax({
    type : "POST",
    url : baseurl+"site/actions/filter/"+companyId,
    data : "site_name="+encodeURIComponent(site_name)+"&company_name="+encodeURIComponent(company_name)+"&site_desc="+encodeURIComponent(site_desc)+"&site_url="+encodeURIComponent(site_url)+"&site_status="+site_status+"&site_date="+site_date+(pageno>1?'&page_no='+pageno:'')+(sort!=""?'&sort_condition='+sort:''),
    async : false,
    cache : false,
    success : function (msg) {
      $("#listingResultset").html(msg);
			 
      var limit = $('#hid_limit').val();
      var page = parseInt(pageno);
      var counter = $("#hid_totalRec").val();
	
      if(counter>0){
        var str="";
        var to = page*limit;
        str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
        if (page > 1) {
          str += '<a href="javascript:void(0)" onclick = "applyFilterAction('+(page-1)+',\''+action+'\',\''+companyId+'\')" class="red"><< Previous</a>';
        }

        if (to < counter) {
          str += ' <span class="red">|</span> <a href="javascript:void(0)" onclick = "applyFilterAction('+(page+1)+',\''+action+'\',\''+companyId+'\')" class="red">Next >></a>';
        }

        $("#pagingdivtop").html(str);
        $("#pagingdivbottom").html(str);
        $("#pagingdivtop").show();
        $("#pagingdivbottom").show();
      }
      return false;
    }
  });
  return false;
}
//function to open dialog box for adding new sites
function addNewSiteDialog (width, height, title) {
  var wid = width;
  var heit = height;
  var buttons = false;
  var companyId = $("#hid_company_id").val();
  $('#dialog').dialog({
    autoOpen: false,
    width: wid,
    height: heit,
    bgiframe: true,
    resizable: false,
    title:title,
    modal: true,
    show: 'puff',
    close: function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h = heit;
  if(buttons){
    h = heit-95;
  }else{
    h = heit-35;
  }
  $('#dialog').css({
    'overflow-y':'auto',
    'width': (wid-18)+'px',
    'height':h+'px'
  }).show();
	
  $('#dialog').html('<div style="padding-top:50px; padding-left:260px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');		
  addEditSite(companyId);
}

//Function to get the individual testimonial to display in detail page
function addEditSite (id) {
  $.ajax({
    type : "GET",
    url : baseurl+'site/actions/new/'+id,
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
        setTimeout( function() {
          $("#edit-site-name").focus();
        } , 1000);
        $("#edit-site-desc").css("width", "318px");
        $("#edit-cancel").click(function (){
          $('#dialog').dialog('destroy');
          return false;
        });
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//function to open dialog box for adding new sites
function editSiteDialog (id, width, height, title) {
  var wid = width;
  var heit = height;
  var buttons = false;
  $('#dialog').dialog({
    autoOpen: false,
    width: wid,
    height: heit,
    bgiframe: true,
    resizable: false,
    title:title,
    modal: true,
    show: 'puff',
    close: function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h = heit;
  if(buttons){
    h = heit-95;
  }else{
    h = heit-35;
  }
  $('#dialog').css({
    'overflow-y':'auto',
    'width': (wid-18)+'px',
    'height':h+'px'
  }).show();
	
  $('#dialog').html('<div style="padding-top:50px; padding-left:260px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');		
  editSite(id, title);
}

//Function to get the individual testimonial to display in detail page
function editSite(id, title){
  reopen_dialog(600,290,"Edit " + title);
  $.ajax({
    type : "GET",
    url : baseurl+'site/edit/'+id,
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
        setTimeout( function() {
          $("#edit-site-name").focus();
        } , 1000);
        $("#edit-site-desc").css("width", "318px");
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}
function editSiteAction(id){
  var action;
  var site_name 			= $.trim($("#edit-site-name").val());
  var site_desc 			= $("#edit-site-desc").val();
  var site_url  			= $.trim($("#edit-site-url").val());
  var site_contact_email  = $.trim($("#edit-site-contact-email").val());
	
  if (site_name == "") {
    styleStatusMessages("Please enter the site name", "statusMessage", "failure");
    return false;
  }
  if (site_url == "") {
    styleStatusMessages("Please enter the site url", "statusMessage", "failure");
    return false;
  }
  if ($.trim(site_url) != "") {
        if (!isWeburl(site_url)) {
             styleStatusMessages("Please enter valid site url.", "statusMessage", "failure");
             return false;
        }
  }
  if (site_contact_email == "") {
    styleStatusMessages("Please enter the site contact email", "statusMessage", "failure");
    return false;
  }
  if ($.trim(site_contact_email) != "") {
        if (!validateEmail(site_contact_email)) {
             styleStatusMessages("Please enter the valid contact email", "statusMessage", "failure");
             return false;
        }
  }
		
  var content = $('#dialog').html();
  var limit = $('#hid_limit').val();
  var counter = parseInt($("#hid_totalRec").val());

  $('#dialog').html('<div style="padding-top:90px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type: "POST",
    url: baseurl + 'site/edit_action',
    data: '&site_id='+encodeURIComponent(id)+'&site_name='+encodeURIComponent(site_name)+'&site_desc='+encodeURIComponent(site_desc) + '&site_url=' + encodeURIComponent(site_url) + '&site_contact_email=' + encodeURIComponent(site_contact_email),
    success: function(msg){
      eval("var json="+msg);
      //$('#dialog').dialog('destroy');
      if(json.Message=="Success"){
        var action;
        $('#dialog').dialog('destroy');
        var path = location.pathname;
        var arg_3 = path.split('/')[3];
        if (arg_3 > 0) {
          applyFilterAction(1, action, json.CompanyId);
        }
        else {
          reloadListingData(limit, 1, "", counter, baseurl + "site","page");
        }
      }else{
        if(json.Error=="Site name is not unique"){
          $('#dialog').html(content);
          $('#edit-site-name').val(site_name);
          $('#edit-site-desc').val(site_desc);
          $('#edit-site-url').val(site_url);
          $('#edit-site-contact-email').val(site_contact_email);
          resize_dialog(600, 290+30);
          styleStatusMessages("Site name already exists", "statusMessage", "failure");
        }
      }
      return false;
    },
    error: function(xhr, desc, err) {
      openAlertDialog(300,200,"Site Existing", "Same Site is Existing");
      return false;
    }
  });
  return false;
}	
//Function to save the data for sites
function submitSite() {
  var site_name = $.trim($("#edit-site-name").val());
  var site_desc = $("#edit-site-desc").val();
  var site_url  = $.trim($("#edit-site-url").val());
  var site_contact_email  = $.trim($("#edit-site-contact-email").val());
  var site_status  = $.trim($("#edit-site-status").val());
  var companyId = $("#hid_company_id").val();
  var action;
	
  if (site_name == "") {
    styleStatusMessages("Please enter the site name", "statusMessage", "failure");
    return false;
  }
  if (site_url == "") {
    styleStatusMessages("Please enter the site url", "statusMessage", "failure");
    return false;
  }
  if ($.trim(site_url) != "") {
        if (!isUrl(site_url)) {
             styleStatusMessages("Please enter valid site url.", "statusMessage", "failure");
             return false;
        }
  }
  if (site_contact_email == "") {
    styleStatusMessages("Please enter the site contact email", "statusMessage", "failure");
    return false;
  }
  if (site_contact_email != "") {
        if (!validateEmail(site_contact_email)) {
             styleStatusMessages("Please enter the valid contact email", "statusMessage", "failure");
             return false;
        }
  }

  $.ajax({
    type: "POST",
    url: baseurl + 'site/update/'+companyId,
    data: '&company_id='+encodeURIComponent(companyId)+'&site_name='+encodeURIComponent(site_name) + '&site_desc=' + encodeURIComponent(site_desc) + '&site_url=' + site_url + '&site_contact_email=' + site_contact_email + '&site_status=' + site_status,
    success: function(msg){
      eval("var json="+msg);
      if(json.Message=="Success"){
        $('#dialog').dialog('destroy');
        applyFilterAction(1, action, companyId);
      }else{
          if(json.Error=="SiteName Not Unique"){
              $.ajax({
                type : "GET",
                url : baseurl+'site/actions/new/'+companyId,
                cache : false,
                success : function (res) {
                  $('#dialog').html(res);
                  $('#edit-site-name').val(site_name);
                  $('#edit-site-desc').val(site_desc);
                  $('#edit-site-url').val(site_url);
                  $('#edit-site-contact-email').val(site_contact_email);
                  $('#edit-site-status').val(site_status);
                  styleStatusMessages("Site name already exists", "statusMessage", "failure");
                },
                error : function (res) {
                  handleRequestError(res);
                }
              });
              resize_dialog(600, 310+30);
          }
      }
    },
    error: function() {
      openAlertDialog(300,200,"Site Existing", "Site name already exists");
      return false;
    }
  });
  return false;
}

//Function to open view detail dialog box
function openViewDetailDialog(id, legalentityid, width, height, title){
  var wid = width;
  var heit = height;
  var buttons = false;
  $('#dialog').dialog({
    autoOpen: false,
    width: wid,
    height: heit,
    bgiframe: true,
    resizable: false,
    title:title,
    modal: true,
    show: 'puff',
    close: function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h = heit;
  if(buttons){
    h = heit-95;
  }else{
    h = heit-40;
  }
  $('#dialog').css({
    'overflow-y':'auto',
    'width': (wid-16)+'px',
    'height':h+'px'
  }).show();
  var loading_width = Math.round(wid/2);
  var loading_height = Math.round(heit/2);
  if (loading_width > 35) {
    loading_width = loading_width - 35; // To show the loader at the center of dialog window.
  }
  if (loading_height > 35) {
    loading_height = loading_height - 45; // To show the loader at the center of dialog window.
  }
  $('#dialog').html('<div style="padding-top:'+loading_height+'px; padding-left:'+loading_width+'px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  siteView(id, legalentityid);
}

//Function to list the site information
function siteView (siteid, legalentityid) {
  //AJAX call to load the site data based on the site id
  $.ajax({
    type : "GET",
    url : baseurl+'site/detail/'+siteid + '/' + legalentityid,
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}
function activateSite(id, status){
  $('#dialog').html('<div style="padding-top:90px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
  var pageno = $("#hid_pageno").val();
   var legaleid = $("#hid_company_id").val();
  if(status=="Active"){
    status = "Inactive";
  }
  else {
    status = "Active";
  }

  $.ajax({
    type : "POST",
    url : baseurl+"site/actions/activate/"+id,
    data: "status="+status,
    async : false,
    cache : false,
    success : function (msg) {
      eval("var json="+msg);
      if(json.Message=="Success"){
        var action;
        openViewDetailDialog(id, legaleid, 550, 300, 'Site Detail');
        applyFilterAction(pageno, 'action', json.CompanyId);
        return false;
      }
    }
  });
}

//function to open dialog box for adding new sites
function addNewCompanyDialog (id, width, height, title) {
  var wid = width;
  var heit = height;
  var buttons = false;
  $('#dialog').dialog({
    autoOpen: false,
    width: wid,
    height: heit,
    bgiframe: true,
    resizable: false,
    title:title,
    modal: true,
    show: 'puff',
    close: function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h = heit;
  if(buttons){
    h = heit-95;
  }else{
    h = heit-35;
  }
  $('#dialog').css({
    'overflow-y':'auto',
    'width': (wid-18)+'px',
    'height':h+'px'
  }).show();

  var loading_width = Math.round(wid/2);
  var loading_height = Math.round(heit/2);
  if (loading_width > 35) {
    loading_width = loading_width - 35; // To show the loader at the center of dialog window.
  }
  if (loading_height > 35) {
    loading_height = loading_height - 45; // To show the loader at the center of dialog window.
  }

  $('#dialog').html('<div style="padding-top:'+loading_height+'px; padding-left:'+loading_width+'px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  addEditCompany(id);
}

//Function to get the individual testimonial to display in detail page
function addEditCompany (id) {
  $.ajax({
    type : "GET",
    url : baseurl+'companies/add',
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
        $("#edit-company-desc").css("width", "318px");
        setTimeout( function() {
          $("#edit-company-name").focus();
        } , 1000);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to save the data for sites
function submitCompany() {
  var action;
  var company_name = $.trim($("#edit-company-name").val());
  var company_desc = $("#edit-company-desc").val();
  var company_url  = $.trim($("#edit-company-url").val());
  var company_contact_email  = $.trim($("#edit-company-contact-email").val());
  var company_status  = $.trim($("#edit-company-status").val());
	
  if (company_name == "") {
    styleStatusMessages("Please enter the legal entity name", "statusMessage", "failure");
    return false;
  }
  if (company_url == "") {
    styleStatusMessages("Please enter the legal entity url", "statusMessage", "failure");
    return false;
  }
  if ($.trim(company_url) != "") {
        if (!isUrl(company_url)) {
             styleStatusMessages("Please enter valid legal entity url.", "statusMessage", "failure");
             return false;
        }
  }
  if (company_contact_email == "") {
    styleStatusMessages("Please enter the legal entity contact email", "statusMessage", "failure");
    return false;
  }
  if (company_contact_email != "") {
        if (!validateEmail(company_contact_email)) {
             styleStatusMessages("Please enter the valid contact email.", "statusMessage", "failure");
             return false;
        }
  }
  var limit = $('#hid_limit').val();
  // Since new legal entity is added, incrementing the counter by one
  var counter = parseInt($("#hid_totalRec").val()) + 1;
  
  var content = $('#dialog').html();
  $('#dialog').html('<div style="padding-top:90px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type: "POST",
    url: baseurl + 'companies/add_action',
    data: '&company_name='+encodeURIComponent(company_name)+'&company_desc='+encodeURIComponent(company_desc) + '&company_url=' + encodeURIComponent(company_url) + '&company_contact_email=' + encodeURIComponent(company_contact_email) + '&company_status=' + encodeURIComponent(company_status),
    success: function(msg){
      eval("var json="+msg);
      //$('#dialog').dialog('destroy');
      if(json.Message=="Success"){
        var action;
        $('#dialog').dialog('destroy');
        // applyCompanyFilterAction(1, action);        
        reloadListingData(limit, 1, "", counter, baseurl + "companies","page");
      }else{
        if(json.Error=='Legal Entity name is not unique'){
          $('#dialog').html(content);
          $('#edit-company-name').val(company_name);
          $('#edit-company-desc').val(company_desc);
          $('#edit-company-url').val(company_url);
          $('#edit-company-contact-email').val(company_contact_email);
          resize_dialog(600, 310+30);
          styleStatusMessages("Legal entity name already exists", "statusMessage", "failure");
        }
      }
      return false;
    },
    error: function(xhr, desc, err) {
      openAlertDialog(300,200,"Legal entity Existing", "Same legal entity is Existing");
      return false;
    }
  });
  return false;
}


function applyCompanyFilterAction(pageno, action){

  //prepare the field values for filtering
  var company_name      = $.trim($("#edit-comp-search-name").val());
  var company_desc      = $.trim($("#edit-comp-search-desc").val());
  var company_url       = $.trim($("#edit-comp-search-url").val());
  var company_status    = $("#edit-comp-search-status").val();
  var company_date	= $("#edit-comp-search-date").val();
  var sortval           = $('#hid_sort').val();
	
  //check for search criteria and return false if no value
  if (company_name == "" && company_desc == "" && company_url == "" && company_status == "") {
    openAlertDialog(300, 125, 'Information', 'Please enter the search criteria');
    return false;
  }

  $('#listingResultset').html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  $("#pagingdivtop").hide();
  $("#pagingdivbottom").hide();

  $.ajax({
    type : "POST",
    url : baseurl+"companies/actions/filter",
    data : "company_name="+encodeURIComponent(company_name)+"&company_desc="+encodeURIComponent(company_desc)+"&company_url="+encodeURIComponent(company_url)+"&company_status="+company_status+"&company_date="+company_date+(pageno>1?'&page_no='+pageno:'')+(sortval!=""?'&sort_condition='+sortval:''),
    async : false,
    cache : false,
    success : function (msg) {

      $("#listingResultset").html(msg);
			 
      var limit = $('#hid_limit').val();
      var page = parseInt(pageno);
      var counter = $("#hid_totalRec").val();
      if(counter>0){
        var str="";
        var to = page*limit;
        str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
        if (page > 1) {
          str += '<a href="javascript:void(0)" onclick = "applyCompanyFilterAction('+(page-1)+',\''+action+'\')" class="red"><< Previous</a>';
        }

        if (to < counter) {
          str += ' <span class="red">|</span> <a href="javascript:void(0)" onclick = "applyCompanyFilterAction('+(page+1)+',\''+action+'\')" class="red">Next >></a>';
        }

        $("#pagingdivtop").html(str);
        $("#pagingdivbottom").html(str);
        $("#pagingdivtop").show();
        $("#pagingdivbottom").show();
      }
		
    }
  });

}
//Function to open view detail dialog box
function openViewCompanyDetailDialog(id, width, height, title){
  var wid = width;
  var heit = height;
  var buttons = false;
  $('#dialog').dialog({
    autoOpen: false,
    width: wid,
    height: heit,
    bgiframe: true,
    resizable: false,
    title:title,
    modal: true,
    show: 'puff',
    close: function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h = heit;
  if(buttons){
    h = heit-95;
  }else{
    h = heit-40;
  }
  $('#dialog').css({
    'overflow-y':'auto',
    'width': (wid-16)+'px',
    'height':h+'px'
  }).show();

  $('#dialog').html('<div style="padding-top:50px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  companyView(id);
}

//Function to list the site information
function companyView (companyid) {
  //AJAX call to load the site data based on the site id
  $.ajax({
    type : "GET",
    url : baseurl+'companies/detail/'+companyid,
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}
// Activate / Deactivate legal entity
function activateCompany(id, status){
  if (status == 'Active') {
     openConfirmBox(function(){
          $('#dialog').html('<div style="padding-top:90px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
          var pageno = $("#hid_pageno").val();
          var limit = $('#hid_limit').val();
          var counter = parseInt($("#hid_totalRec").val());

          if(status=="Active"){
            status = "Inactive";
          }
          else {
            status = "Active";
          }

          $.ajax({
            type : "POST",
            url : baseurl+"companies/actions/activate/"+id,
            data: "status="+status,
            async : false,
            cache : false,
            success : function (msg) {
              if(msg=="Success"){
                var action;
                openViewCompanyDetailDialog(id, 500, 250, 'Legal Entity Detail');
                //applyCompanyFilterAction(pageno, action);
                reloadListingData(limit, 1, "", counter, baseurl + "companies","page");
              }
            }
          });
        $('#alertdialog').dialog('destroy');
        }, 300, 120, "Confirm Deactivate", "All sites mapped to this legal entity will be deactivated.");
  }
  else {
      $('#dialog').html('<div style="padding-top:90px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
      var pageno = $("#hid_pageno").val();
      var limit = $('#hid_limit').val();
      var counter = parseInt($("#hid_totalRec").val());

      if(status=="Active"){
        status = "Inactive";
      }
      else {
        status = "Active";
      }

      $.ajax({
        type : "POST",
        url : baseurl+"companies/actions/activate/"+id,
        data: "status="+status,
        async : false,
        cache : false,
        success : function (msg) {
          if(msg=="Success"){
            var action;
            openViewCompanyDetailDialog(id, 500, 250, 'Legal Entity Detail');
            //applyCompanyFilterAction(pageno, action);
            reloadListingData(limit, 1, "", counter, baseurl + "companies","page");
          }
        }
      });
  }
}
function loadSites(companyId){
  var action;
  $('#dialog').dialog('destroy');
  window.parent.location = baseurl + 'site/' + companyId;
}

//Function to redirect the page
function redirectWorkflow (url) {
	$('#dialog').dialog('destroy');
	window.location.href = url;
}

//function to open dialog box for adding new sites
function editCompanyDialog (id, width, height, title) {
  var wid = width;
  var heit = height;
  var buttons = false;
  $('#dialog').dialog({
    autoOpen: false,
    width: wid,
    height: heit,
    bgiframe: true,
    resizable: false,
    title:title,
    modal: true,
    show: 'puff',
    close: function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h = heit;
  if(buttons){
    h = heit-95;
  }else{
    h = heit-35;
  }
  $('#dialog').css({
    'overflow-y':'auto',
    'width': (wid-18)+'px',
    'height':h+'px'
  }).show();
	
  $('#dialog').html('<div style="padding-top:50px; padding-left:260px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');		
  editCompany(id);
}

//Function to get the individual testimonial to display in detail page
function editCompany(id){
  reopen_dialog(600,290,"Edit Legal Entity");
  $.ajax({
    type : "GET",
    url : baseurl+'companies/edit/'+id,
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
        $("#edit-company-desc").css("width", "318px");
        setTimeout( function() {
          $("#edit-company-name").focus();
        } , 1000);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}
function editCompanyAction(id){
  var action;
  var company_name 		= $.trim($("#edit-company-name").val());
  var company_desc 		= $("#edit-company-desc").val();
  var company_url  		= $.trim($("#edit-company-url").val());
  var company_contact_email  	= $.trim($("#edit-company-contact-email").val());
	
  if (company_name == "") {
    styleStatusMessages("Please enter the legal entity name", "statusMessage", "failure");
    return false;
  }
  if (company_url == "") {
    styleStatusMessages("Please enter the legal entity url", "statusMessage", "failure");
    return false;
  }
  if ($.trim(company_url) != "") {
        if (!isUrl(company_url)) {
             styleStatusMessages("Please enter valid legal entity url.", "statusMessage", "failure");
             return false;
        }
  }
  if (company_contact_email == "") {
    styleStatusMessages("Please enter the legal entity contact email", "statusMessage", "failure");
    return false;
  }
  if (company_contact_email != "") {
        if (!validateEmail(company_contact_email)) {
             styleStatusMessages("Please enter the valid contact email.", "statusMessage", "failure");
             return false;
        }
  }


  var limit = $('#hid_limit').val();
  var counter = parseInt($("#hid_totalRec").val());
		
  var content = $('#dialog').html();
  $('#dialog').html('<div style="padding-top:90px; padding-left:275px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type: "POST",
    url: baseurl + 'companies/companies_edit_action',
    data: '&company_id='+encodeURIComponent(id)+'&company_name='+encodeURIComponent(company_name)+'&company_desc='+encodeURIComponent(company_desc) + '&company_url=' + encodeURIComponent(company_url) + '&company_contact_email=' + encodeURIComponent(company_contact_email),
    success: function(msg){
      eval("var json="+msg);
      if(json.Message=="Success"){
        var action;
        $('#dialog').dialog('destroy');
        //applyCompanyFilterAction(1, action);
        reloadListingData(limit, 1, "", counter, baseurl + "companies","page");
      }else{
        if(json.Error=="Legal Entity name is not unique"){
          $('#dialog').html(content);
          $('#edit-company-name').val(company_name);
          $('#edit-company-desc').val(company_desc);
          $('#edit-company-url').val(company_url);
          $('#edit-company-contact-email').val(company_contact_email);
          resize_dialog(600, 290+30);
          styleStatusMessages("Legal entity name already exist", "statusMessage", "failure");
        }
      }
      return false;
    },
    error: function() {
      openAlertDialog(300,200,"Legal entity Existing", "Same legal entity is Existing");
      return false;
    }
  });
  return false;
}

/**
 * Function to sort
 * @param string module 	val: site or companies
 */
function sortListColumn(module, sortField, companyId){
  $("#listingResultset").html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  var limit = 10;
  var hid_sort = $('#hid_sort').val();
  var orig_sort = sortField;
  var pageno = parseInt($('#hid_pageno').val());
  var urls = "";
  var data = eval("filterdata_"+module+"();");
  if(hid_sort){
    hid_sort = hid_sort.split(",");
    if(hid_sort[1] == sortField ){
      if(hid_sort[0]=="ascending")
        sortField = ["descending", sortField];
      else
        sortField = ["ascending", sortField];
    }else{
      sortField = ["ascending", sortField];
      $('#srt_'+hid_sort[1]).attr('class','sortNone');
    }
  }else{
    sortField = ["ascending", sortField];
  }
  urls = module + "/actions/filter";
  var action = "";

  $.ajax({
    type : "POST",
    url : baseurl+urls,
    data: "limit="+limit+"&page=" + pageno +"&sort_condition="+sortField+data,
    async : false,
    cache : false,
    success : function (msg) {
      $("#listingResultset").html(msg);
      $('#srt_'+orig_sort).attr('class', sortField[0]=="ascending"?"sortAsc":"sortDsc");
      $('#hid_sort').val(sortField);
      refresh_list_pagination(module, companyId, pageno, action);
    }
  });
  return false;
}

function refresh_list_pagination(module, companyId, pageno, action){
  var limit = $('#hid_limit').val();
  var page = parseInt(pageno);
  var counter = $('#hid_totalRec').val();

  if(counter>0){
    var str="";
    var to = page*limit;
    str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
    if(module == 'site') {
      if (page > 1) {
        str += '<b><a href="javascript:void(0)" onclick = "applyFilterAction('+(page-1)+',\''+action+'\',\''+companyId+'\')" class="red"><< Previous</a></b>';
      }

      if (to < counter) {
        str += ' <span class="red"> |</span><b><a href="javascript:void(0)" onclick = "applyFilterAction('+(page+1)+',\''+action+'\',\''+companyId+'\')" class="red">Next >></a></b>';
      }
    }
    else{
      if (page > 1) {
        str += '<b><a href="javascript:void(0)" onclick = "applyCompanyFilterAction('+(page-1)+',\''+action+'\')" class="red"><< Previous</a></b>';
      }

      if (to < counter) {
        str += ' <span class="red"> |</span><b><a href="javascript:void(0)" onclick = "applyCompanyFilterAction('+(page+1)+',\''+action+'\')" class="red">Next >></a></b>';
      }
    }

    $("#pagingdivtop").html(str);
    $("#pagingdivbottom").html(str);
  }else{
    $("#pagingdivtop").html("");
    $("#pagingdivbottom").html("");
  }
}
function filterdata_site(){
  //prepare the field values for filtering
  var site_name 	= $.trim($("#edit-site-search-name").val());
  var site_desc 	= $("#edit-site-search-desc").val();
  var site_url 	= $("#edit-site-search-url").val();
  var site_status = $("#edit-site-search-status").val();
  var site_date	= $("#edit-site-search-date").val();

  var data = "";
  if($.trim(site_name)!=""){
    data+="&site_name="+site_name;
  }
  if($.trim(site_desc)!=""){
    data+="&site_desc="+site_desc;
  }
  if($.trim(site_status)!="" && site_status != "ANY"){
    data+="&site_status="+site_status;
  }
  if($.trim(site_url)!=""){
    data+="&site_url="+site_url;
  }
  if($.trim(site_date)!=""){
    data+="&site_date="+site_date;
  }
  return data;
}
function filterdata_companies(){
  //prepare the field values for filtering
  var company_name 	= $.trim($("#edit-comp-search-name").val());
  var company_desc 	= $.trim($("#edit-comp-search-desc").val());
  var company_url 	= $.trim($("#edit-comp-search-url").val());
  var company_status 	= $("#edit-comp-search-status").val();
  var company_date	= $("#edit-comp-search-date").val();
	
  var data = "";
  if($.trim(company_name)!=""){
    data+="&company_name="+company_name;
  }
  if($.trim(company_desc)!=""){
    data+="&company_desc="+company_desc;
  }
  if($.trim(company_status)!="" && company_status != "ANY"){
    data+="&company_status="+company_status;
  }
  if($.trim(company_url)!=""){
    data+="&company_url="+company_url;
  }
  if($.trim(company_date)!=""){
    data+="&company_date="+company_date;
  }
  return data;
}

function addNewModuleDialog(id, width, height, title) {
  var wid = width;
  var heit = height;
  var buttons = false;
  $('#dialog').dialog({
    autoOpen: false,
    width: wid,
    height: heit,
    bgiframe: true,
    resizable: false,
    title:title,
    modal: true,
    show: 'puff',
    close: function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h = heit;
  if(buttons){
    h = heit-95;
  }else{
    h = heit-35;
  }
  $('#dialog').css({
    'overflow-y':'auto',
    'width': (wid-18)+'px',
    'height':h+'px'
  }).show();
	
  $('#dialog').html('<div style="padding-top:50px; padding-left:260px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');		
  addModule();
}

function manageSiteDialog(id, width, height, title) {
 $('#dialog').dialog('destroy');
  var wid = width;
  var heit = height;
  var buttons = false;
  $('#dialog').dialog({
    autoOpen: false,
    width: wid,
    height: heit,
    bgiframe: true,
    resizable: false,
    title:title,
    modal: true,
    show: 'puff',
    close: function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h = heit;
  if(buttons){
    h = heit-95;
  }else{
    h = heit-35;
  }
  $('#dialog').css({
    'overflow-y':'auto',
    'width': (wid-18)+'px',
    'height':h+'px'
  }).show();
	
  $('#dialog').html('<div style="padding-top:100px; padding-left:260px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  associateModule(id);
}

function associateModule(id){
  $.ajax({
    type : "GET",
    url : baseurl+'site/associate_modules/'+id,
    async : true,
    cache : false,
    success : function (res) {
        $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}
function submitAssociation(id){
  var i;
  var moduleForm 	= document.moduleForm;
  var elLength 	= moduleForm.elements.length;
  var output 		= "";
  for(i=0; i<elLength; i++){
    var type 		= moduleForm.elements[i].type;
    var checkstat 	= moduleForm.elements[i].checked;
    var checkVal	= moduleForm.elements[i].value;
    var checkName	= moduleForm.elements[i].name;
    if(type=="checkbox" && checkstat){
      if(output == ""){
        output = checkVal;
      }else{
        output = output + ',' + checkVal;
      }
    }
  }
		
  var content = $('#dialog').html();
  $('#dialog').html('<div style="padding-top:90px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type: "POST",
    url: baseurl + 'site/association_action',
    data: '&siteId='+id+'&savedata='+encodeURIComponent(output),
    success: function(msg){
      eval("var json="+msg);
      if(json.Message=="Success"){
        $('#dialog').dialog('destroy');
        openAlertDialog(350, 150, 'Information', 'Module associations saved successfully', 'success');
      }
      return false;
    }
  });
  return false;
	
}

function closeDialog(){
  $('#dialog').dialog('destroy');
}

function generateKey(siteid, sitename){
  openConfirmBox(function(){
    $.ajax({
      type: "GET",
      url: baseurl + 'sitemodules/authkey/'+siteid,
      success: function(msg){
        if(msg=="Success"){
          $('#alertdialog').dialog('destroy');
          reopen_dialog(550,300,sitename);
          siteView(siteid)
          openAlertBox(300, 125, 'Information', 'Site authorization key regenerated successfully');
        }
        return false;
      },
      error : function (res) {
        handleRequestError(res);
      }
    });
  },300,100,"Confirm Re-generate","Do you want to regenerate authorization key?");
}

/**
 * Go back to site info
 */
function back_to_site(siteid, entityid, sitename) {
  $('#dialog').html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "GET",
    url : baseurl + 'site/detail/' + siteid + '/' + entityid,
    async : true,
    cache : false,
    success : function (res) {
       reopen_dialog(550, 300, sitename);
       $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}